package com.study.springsecurity.utils;

import com.study.springsecurity.entity.MyUserDetails;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import java.util.Collection;
import java.util.Objects;

/**
 * 当前用户信息获取工具类
 *
 * @Author YL
 * @Create 2022/10/21 23:26
 * @Version 1.0
 */
public class SecurityContextUtil {

    /**
     * 获取用户认证信息
     *
     * @return
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            throw new RuntimeException("用户未登录");
        }
        return authentication;
    }


    /**
     * 获取身份验证请求的其他详细信息
     *
     * @return
     */
    public static WebAuthenticationDetails getUserDetails() {
        Authentication authentication = getAuthentication();
        return (WebAuthenticationDetails) authentication.getDetails();
    }

    /**
     * 获取用户信息，包含账号、用户id
     *
     * @return
     */
    public static MyUserDetails getUserPrincipal() {
        Authentication authentication = getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            return (MyUserDetails) authentication.getPrincipal();
        }
        throw new RuntimeException("用户未登录");
    }

    /**
     * 获取用户userId
     *
     * @return
     */
    public static Long getUserId() {
        return getUserPrincipal().getUserId();
    }

    /**
     * 获取用户名称
     *
     * @return
     */
    public static String getUserName() {
        return getAuthentication().getName();
    }

    /**
     * 获取用户权限
     *
     * @return
     */
    public static Collection<GrantedAuthority> getUserAuth() {
        return getUserPrincipal().getAuthorities();
    }

    /**
     * 获取请求ip
     *
     * @return
     */
    public static String getRequestIp() {
        return getUserDetails().getRemoteAddress();
    }

    /**
     * 获取请求session
     *
     * @return
     */
    public static String getRequestSession() {
        return getUserDetails().getSessionId();
    }
}
